package com.chenailin.www.controller.article;

import com.chenailin.www.model.dto.CommentDTO;
import com.chenailin.www.model.pojo.Comment;
import com.chenailin.www.model.vo.CommentVO;
import com.chenailin.www.model.vo.ResultVO;
import com.chenailin.www.service.CommentService;
import com.chenailin.www.serviceimpl.CommentServiceImpl;
import com.chenailin.www.util.JsonUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author evi
 */
@WebServlet("/comment/*")
public class CommentController extends HttpServlet {
    private final CommentService commentService = new CommentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set response content type
        resp.setContentType("application/json;charset=UTF-8");
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/comment/article/")) {
                // Get comments for an article
                Long articleId = Long.parseLong(path.substring("/comment/article/".length()));
                System.out.println("111");
                List<CommentVO> comments = commentService.getCommentsByArticle(articleId);
                System.out.println("222");
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(comments)));
            } else if (path.startsWith("/comment/user/")) {
                // Get comments by a user (only allowed for admin or the user themselves)
                Long targetUserId = Long.parseLong(path.substring("/comment/user/".length()));

                // Authorization check - only allow if admin or the user themselves
                if (userId.equals(targetUserId)) {
                    List<CommentVO> comments = commentService.getCommentsByUser(targetUserId);
                    resp.getWriter().write(JsonUtil.toJson(ResultVO.success(comments)));
                } else {
                    resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    resp.getWriter().write(JsonUtil.toJson(ResultVO.error(403, "Unauthorized access")));
                }
            } else if (path.startsWith("/comment/")) {
                // Get a specific comment
                Long commentId = Long.parseLong(path.substring("/comment/".length()));
                CommentVO comment = commentService.getCommentById(commentId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(comment)));
            } else {
                // Invalid path
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid request path")));
            }
        } catch (NumberFormatException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid ID format")));
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(500, e.getMessage())));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set response content type
        resp.setContentType("application/json;charset=UTF-8");
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            // Create new comment
            CommentDTO dto = JsonUtil.fromJson(IOUtils.toString(req.getReader()), CommentDTO.class);
            Comment comment = commentService.addComment(dto, userId);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.success(comment)));
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(500, e.getMessage())));
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set response content type
        resp.setContentType("application/json;charset=UTF-8");
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/comment/")) {
                Long commentId = Long.parseLong(path.substring("/comment/".length()));
                CommentDTO dto = JsonUtil.fromJson(IOUtils.toString(req.getReader()), CommentDTO.class);
                Comment updatedComment = commentService.updateComment(commentId, dto, userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success(updatedComment)));
            } else {
                // Invalid path
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid request path")));
            }
        } catch (NumberFormatException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid ID format")));
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(500, e.getMessage())));
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set response content type
        resp.setContentType("application/json;charset=UTF-8");
        String path = req.getRequestURI().substring(req.getContextPath().length());
        Long userId = (Long) req.getSession().getAttribute("userId");

        try {
            if (path.startsWith("/comment/")) {
                Long commentId = Long.parseLong(path.substring("/comment/".length()));
                commentService.deleteComment(commentId, userId);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.success("Comment deleted successfully")));
            } else {
                // Invalid path
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid request path")));
            }
        } catch (NumberFormatException e) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "Invalid ID format")));
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(500, e.getMessage())));
        }
    }
}